<template>
  <a-drawer :open="visibleData" title="协议条款核对" @close="onClose">
    <template #closeIcon>
      <div class="express-bar"></div>
      <div class="express-btn">
        <CloseCircleOutlined :size="32" @click="onClose" />
      </div>
    </template>
    <a-card size="small" :title="detailList.agreement_name">
      <template #extra
        ><span>已核算{{ detailList.accounting_record_num || 0 }}次</span><span style="margin-left: 10px">上次核算：{{ detailList.last_accounting_time }}</span></template
      >
      <a-table :dataSource="dataListOne" :columns="columns" :pagination="false" rowKey="id" size="small" bordered :showExpandColumn="false" expandRowByClick>
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'check_date'">
            <a-select v-model:value="record.check_date" style="width: 150px" placeholder="请选择" :showSearch="true" :allowClear="true" optionFilterProp="label" @change="onChange">
              <a-select-option v-for="item in detailList.cycle_dates" :key="item" :value="item" :label="item" :disabled="isDisabled(item)">
                {{ item }}
              </a-select-option>
            </a-select>
          </template>
        </template>
      </a-table>
    </a-card>
    <a-card size="small" title="陈列情况" style="margin-top: 10px">
      <a-descriptions size="small" :column="6">
        <a-descriptions-item v-for="(record, index) in detailList.display_check_record" :key="index">
          <div class="image-container">
            <!-- <a-image :preview="{ visible: visible === index, onVisibleChange: (vis) => (visible = vis) }" :width="150" :src="record.check_pic.split(',')[0] || failImg" @click="visible = index" /> -->
            <a-image-preview-group>
              <a-image :width="150" v-for="(item, imgIndex) in record.check_pic.split(',')" :key="imgIndex" :src="item || failImg" />
            </a-image-preview-group>
            <div class="overlay">
              <div class="text">检核人： {{ record.salesman.rename }}</div>
              <div class="text">时间： {{ record.check_date }}</div>
            </div>
          </div>
          <div style="display: none">
            <a-image-preview-group :preview="{ visible: visible === index, onVisibleChange: (vis) => (visible = vis) }">
              <a-image v-for="(item, imgIndex) in record.check_pic.split(',')" :key="imgIndex" :src="item || failImg" @click="visible = index" />
            </a-image-preview-group>
          </div>
        </a-descriptions-item>
      </a-descriptions>
    </a-card>
    <a-card size="small" title="历史核算" style="margin-top: 10px">
      <a-table :dataSource="detailList.accounting_record" :columns="columnsTwo" :pagination="false" rowKey="id" size="small" bordered :showExpandColumn="false" expandRowByClick>
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'check_status'">
            {{ text == 1 ? '通过' : '未通过' }}
          </template>
          <template v-if="column.dataIndex === 'action'">
            <a-button danger type="link" @click="refuseCheck(record.id)">驳回</a-button>
          </template>
        </template>
      </a-table>
    </a-card>
    <template #footer>
      <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
      <a-button type="primary" @click="onSubmit">通过</a-button>
    </template>
  </a-drawer>
</template>

<script setup lang="ts">
import { displayApi } from '@/api/business/marketing/display-api'
import { message } from 'ant-design-vue'
import { useLoadingStore } from '@/store/modules/loading-store'
import { errorSentry } from '@/lib/error-sentry'
import failImg from '@/assets/images/notice/failImg.png'
const loadingStore = useLoadingStore()
defineExpose({
  showDrawer
})
const emit = defineEmits(['reload-list'])

// --------------------- Drawer 显示与隐藏 ---------------------
// 是否展示
const visible = ref(false)
const visibleData = ref(false)
// 详情
const options = ref({})
const detailList = ref({})
const dataListOne = ref([])

function showDrawer(item) {
  options.value = item
  detailData(item)
  dataListOne.value.push({})
  visibleData.value = true
}

const detailData = async (val) => {
  detailList.value = {}
  try {
    const res = await displayApi.agreementCycleDetail({ id: val.id })
    detailList.value = res.data
  } catch (e) {
    if (e.status == 500) {
      message.error(e.response.data.message)
    } else {
      message.error(e.msg)
    }

    errorSentry.captureError(e)
  }
}

const onChange = (val) => {
  const filteredData = detailList.value.display_cycle_detail[val]
  // 初始化结果对象
  const result = { goods: '', cash: '' }

  // 遍历filteredData并处理
  filteredData.forEach((item) => {
    if (item.type === 1) {
      // 如果type为1，将cycle_num加入cash字符串，用逗号分隔
      result.cash += `${item.cycle_num}, `
    } else if (item.type === 2) {
      // 如果type为2，将name和cycle_num合并到goods字符串
      result.goods += `${item.name}*${item.cycle_num}, `
    }
  })

  // 去掉goods和cash字符串末尾多余的逗号和空格
  result.goods = result.goods.trim().slice(0, -1)
  result.cash = result.cash.trim().slice(0, -1)
  dataListOne.value[0].goods = result.goods
  dataListOne.value[0].cash = result.cash
}

const isDisabled = (value) => {
  // 检查 accounting_record 数组中是否存在相同的 check_date
  return detailList.value.accounting_record.some((record) => record.check_date === value)
}

// --------------------- 驳回 ---------------------
const refuseCheck = async (id: number) => {
  try {
    const res = await displayApi.agreementReject(id)
    message.success(res.msg)
    onClose()
  } catch (e) {
    message.error(e.msg)
    errorSentry.captureError(e)
  }
}

// --------------------- 提交 ---------------------
const onSubmit = async () => {
  try {
    loadingStore.show()
    const data = {
      display_agreement_id: detailList.value.id,
      check_date: dataListOne.value[0].check_date,
      goods: dataListOne.value[0].goods,
      cash: dataListOne.value[0].cash
    }
    const res = await displayApi.agreementExchange(data)
    message.success(res.msg)
    onClose()
    options.value = {}
    detailList.value = {}
    dataListOne.value = []
  } catch (e) {
    message.error(e.msg)
    errorSentry.captureError(e)
  } finally {
    loadingStore.hide()
  }
}

const onClose = () => {
  dataListOne.value = []
  visibleData.value = false
}

// --------------------- 入库商品 ---------------------

const columns = reactive([
  {
    title: '核算周期',
    dataIndex: 'check_date'
  },
  {
    title: '商品',
    dataIndex: 'goods'
  },
  {
    title: '现金',
    dataIndex: 'cash'
  }
])

const columnsTwo = reactive([
  {
    title: '核算周期',
    dataIndex: 'check_date'
  },
  {
    title: '商品',
    dataIndex: 'goods'
  },
  {
    title: '现金',
    dataIndex: 'cash'
  },
  {
    title: '审核状态',
    dataIndex: 'check_status'
  },
  {
    title: '兑付状态',
    dataIndex: ''
  },
  {
    title: '兑付时间',
    dataIndex: ''
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: 180
  }
])
</script>
<style lang="less" scoped>
.image-container {
  position: relative;
  display: inline-block;
  margin-right: 5px;
}

.image-container .overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明背景 */
  color: white;
  padding: 2px;
  font-size: 12px;
  text-align: left;
}

.image-container .text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
